package com.example.exceldemo.liteflowComponent.common;

import com.example.exceldemo.constants.ReqMgrConstants;
import com.example.exceldemo.model.DemoContext;
import com.example.exceldemo.model.ReqInfoDTO;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.util.List;
import java.util.Map;

/**
 * @author yangwb8
 * @Date 2025/5/17 03:49
 */
@Slf4j
@LiteflowComponent("valid")
public class ValidateTemplates extends NodeComponent {

    private static final String DEFAULT_TEMPLATE_DIR = "src/main/resources/template";
    private static final String CLASSPATH_TEMPLATE_GS_DIR = "template/gs";
    private static final String CLASSPATH_TEMPLATE_QH_DIR = "template/qh";

    @Override
    public void process() throws Exception {
        System.out.println("验证模板");
        DemoContext context = this.getContextBean(DemoContext.class);
        Map<String, String> settings = context.getSettings();
        
        // 统一使用类路径方式验证模板，不再区分操作系统
        log.info("统一使用类路径方式验证模板");
        validateTemplatesFromClassPath(context);
    }
    
    /**
     * 从类路径验证模板文件
     *
     * @param context 上下文
     * @throws RuntimeException 如果模板验证失败
     */
    private void validateTemplatesFromClassPath(DemoContext context) {
        String templateDir ="";
        List<ReqInfoDTO> reqInfoDTOS = context.getReqInfoDTOS();
        if (!reqInfoDTOS.isEmpty()){
            ReqInfoDTO reqInfoDTO = reqInfoDTOS.get(0);
            String provCode = reqInfoDTO.getProvCode();
            if (ReqMgrConstants.PROV_CODE_GS.equals(provCode)){
                templateDir = CLASSPATH_TEMPLATE_GS_DIR;
            }else if (ReqMgrConstants.PROV_CODE_QH.equals(provCode)){
                templateDir = CLASSPATH_TEMPLATE_QH_DIR;
            }else{
                throw new RuntimeException("未知的省份编码");
            }
        }
        // 定义必需的模板文件列表
        String[] requiredTemplates = {ReqMgrConstants.TEMPLATE_SELF_TEST, ReqMgrConstants.TEMPLATE_ANALYSIS, ReqMgrConstants.TEMPLATE_FUN_LIST};

        // 检查每个必需模板文件是否存在
        for (String template : requiredTemplates) {
            ClassPathResource resource = new ClassPathResource(templateDir + "/" + template);
            if (!resource.exists()) {
                log.error("类路径中模板文件不存在: {}", templateDir + "/" + template);
                throw new RuntimeException("类路径中模板文件不存在: " + templateDir + "/" + template);
            }
        }
        // 统一使用类路径标识
        context.setTemplateDir("CLASSPATH:" + templateDir);
        log.info("已设置模板目录为类路径: {}", context.getTemplateDir());
    }
}
